<?php
namespace app\common;

use app\BaseController;
use think\Validate;

class Controller extends BaseController
{
    /**
     * 控制器的验证器
     *
     * @var bool
     */
    protected $validate = false;

    /**
     * 初始化数据
     */
    protected function initialize()
    {
    }

    /**
     * 自动验证数据
     * @param array $data
     * @param bool $scene
     * @return bool
     * @throws \ReflectionException
     */
    protected function initValidatorData( $data = [] , $validate = false, $scene = false )
    {
        !$scene && $scene = $this->request->action();
        !$validate && $validate = $this->validate;
        if ( $validate !== false && $this->sences($scene)) {
            $checkData = count($data) === 0 ? $this->request->param() : $data;
            validate($validate)->scene($scene)->check($checkData);
        }
        return true;
    }

    /**
     * @param $scene
     * @return mixed
     * @throws \ReflectionException
     */
    private function sences($scene)
    {
        $validateClass = new \ReflectionClass( $this->validate );
        $validateO = $validateClass->newInstance();
        return $validateO->hasScene($scene);
    }
}
